(function (width, multiple) {
    //rem适配方案
    window.setViewport = function () {
        document.documentElement.style.fontSize = document.documentElement.clientWidth / width * multiple + 'px';
        document.documentElement.style.minHeight = document.documentElement.clientWidth * 1.5 + 'px';
    };
    window.addEventListener("resize", function () {
        setViewport();
    }, false);
    window.addEventListener("orientationchange", function () {
        setViewport();
    }, false);
    setViewport();
})(375, 100);
$(function () {
    (function (width, multiple) {
        //文件路径
        // var api_url = "http://192.168.0.8:8080";
        var api_url = "http://www.zhengcezaishou.com/app";
        //rem转换为px
        window.remToPx = function (rem) {
            return rem * document.documentElement.clientWidth / width * multiple + "px";
        };
        window.remToPxNum = function (rem) {
            return rem * document.documentElement.clientWidth / width * multiple;
        };
        var auth = function () {
            if (getLocalItem('user')) {
                return true;
            } else {
                toast('请先登录');
                removeLocalItem('openWebview');
                openWebview("account-login");
                return false;
            }
        };
        //页面注册
        var webview = {
            "account-forget": {url: "/pages/account/forget/page.html", styles: {}},
            "account-login": {url: "/pages/account/login/page.html", styles: {}},
            "account-mobile": {url: "/pages/account/mobile/page.html", styles: {}},
            "account-register": {url: "/pages/account/register/page.html", styles: {}},
            "account-password": {url: "/pages/account/password/page.html", styles: {}},
            "account-m-password": {url: "/pages/account/mPassword/page.html", styles: {}},
            "common-ads": {url: "/pages/common/ads/page.html", styles: {}},
            "common-footer": {url: "/pages/common/footer/page.html", styles: {}},
            "common-install": {url: "/pages/common/install/page.html", styles: {}},
            "home-index": {url: "/pages/home/index/page.html", styles: {top: 0, bottom: remToPx(0.98)}},
            "home-adapter": {url: "/pages/home/adapter/page.html", styles: {}, auth: auth},
            "home-result": {url: "/pages/home/result/page.html", styles: {}, auth: auth},
            "home-detail": {url: "/pages/home/detail/page.html", styles: {}, auth: auth},
            "home-orderdetail": {url: "/pages/home/orderdetail/page.html", styles: {}, auth: auth},
            "my-collection": {url: "/pages/my/collection/page.html", styles: {}, auth: auth},
            "my-index": {url: "/pages/my/index/page.html", styles: {top: 0, bottom: remToPx(0.98)}},
            "my-info": {url: "/pages/my/info/page.html", styles: {}},
            "my-message": {url: "/pages/my/message/page.html", auth: auth},
            "my-order": {url: "/pages/my/order/page.html", styles: {}, auth: auth},
            "my-orderdetail": {url: "/pages/my/orderdetail/page.html", styles: {}, auth: auth},
            "my-setup": {url: "/pages/my/setup/page.html", styles: {}},
            "my-password": {url: "/pages/my/password/page.html", styles: {}, auth: auth},
            "policies-detail": {url: "/pages/policies/detail/page.html", styles: {}},
            "policies-index": {url: "/pages/policies/index/page.html", styles: {top: 0, bottom: remToPx(0.98)}},
            "times-detail": {url: "/pages/times/detail/page.html", styles: {}},
            "times-index": {url: "/pages/times/index/page.html", styles: {top: 0, bottom: remToPx(0.98)}},
            "videos-detail": {url: "/pages/videos/detail/page.html", styles: {}},
            "videos-index": {url: "/pages/videos/index/page.html", styles: {top: 0, bottom: remToPx(0.98)}}
        }, defStyles = {}, defAniShow = "slide-in-right", defDuration = 300, defShowed = function () {
            removeLocalItem('openWebview');
        };
        base_path = "";
        var current_path = "";
        if (window.location.href.indexOf("/pages/") >= 0) {
            current_path = window.location.href.replace(/.*?\/pages\//, "pages/").replace(/\/.*?$/, "/");
            for (var i = 0; i <= current_path.split("/").length; i++) {
                base_path += "../";
            }
        }
        // 取消浏览器的所有事件，使得active的样式在手机上正常生效
        document.addEventListener('touchstart', function () {
            return false;
        }, false);
        // 禁止选择
        document.oncontextmenu = function () {
            return false;
        };
        // DOMContentLoaded事件处理
        document.addEventListener('DOMContentLoaded', function () {
            document.body.onselectstart = function () {
                return false;
            };
        }, false);
        //引入资源文件
        window.builder = function (tag) {
            var element = document.createElement(tag);
            var _this = {
                build: function () {
                    return element;
                },
                attr: function (attr, value) {
                    attr && value && (element[attr] = value);
                    return _this;
                },
                html: function (text) {
                    text && (element.innerHTML = text);
                    return _this;
                },
                append: function (ele) {
                    ele && element.append(ele);
                    return _this;
                }
            };
            return _this;
        };
        //ajax二次封装实现全局接口统一处理
        window.ajax = function (url, options, dispatcher) {
            if (typeof url === "object") {
                dispatcher = options;
                options = url;
                options.url = api_url + options.url;
                url = undefined;
            } else {
                url = api_url + url;
            }
            options = options || {};
            options.waiting === false || getLocalItem('waiting') || dispatcher || showWaiting();
            var user = getLocalItem("user");
            if (user) {
                options.headers.token = user.token;
            }
            var success = options.success, error = options.error, complete = options.complete;
            options.success = function (data, textStatus, jqXHR) {
                options.waiting === false || dispatcher || closeWaiting();
                data = new Result(data);
                switch (data.code) {
                    case 4:
                    case "4": {
                        closeWebview();
                        break;
                    }
                    case 100:
                    case"100": {
                        toast(data.msg);
                        tokenExpires();
                        break;
                    }
                    default: {
                        success && success(data, textStatus, jqXHR);
                    }
                }
                complete && complete();
            };
            options.error = function (jqXHR, textStatus, thrownError) {
                dispatcher || closeWaiting();
                toast("网络请求错误！");
                error && error(jqXHR, textStatus, thrownError);
                complete && complete();
            };
            options.complete = function () {
            };
            dispatcher ? dispatcher.ajax(url, options) : $.ajax(url, options);
        };
        //取消浏览器的所有事件，使得active的样式在手机上正常生效
        document.addEventListener('touchstart', function () {
            return false;
        }, true);
        //H5支持方法封装
        window.exit = function () {
            confirm('确认退出？') && window.close();
        };
        window.log = function () {
            console.log(arguments);
        };
        window.currentWebview = function () {
            return {id: true};
        };
        window.openWebview = function (id, params) {
            window.location.href = base_path + "." + webview[id].url + "?" + $.objToParam(params);
        };
        window.closeWebview = function (id) {
            id || window.history.back();
        };
        window.reloadWebview = function (id) {
            location.reload();
        };
        window.reloadLaunchWebview = function () {
        };
        window.logout = function () {
            removeLocalItem("user");
        };
        window.tokenExpires = function () {
            logout();
            openWebview("account-login");
        };
        window.toast = function (message) {
            alert(message);
        };
        window.play = function (url) {
            window.open(url);
        };
        window.dial = function (number, confirm) {
            window.open("tel:" + number);
        };
        window.setLocalItem = function (key, item) {
            localStorage.setItem(key, JSON.stringify(item));
        };
        window.getLocalItem = function (key) {
            return localStorage.getItem(key) && JSON.parse(localStorage.getItem(key));
        };
        window.removeLocalItem = function (key) {
            localStorage.removeItem(key);
        };
        window.showWaiting = function () {
        };
        window.closeWaiting = function () {
        };
        window.previewImage = function (urls, current, loop) {
            for (var i in urls) {
                window.open(urls[i]);
            }
        };
        window.share = function () {

        };
        window.evalJs = function () {

        };
        // 从相册中选择图片
        window.galleryImg = function (callback) {

        };
        window.upload = function () {

        };
        //获取客户端推送标识信息
        window.getClientInfo = function () {
            return 'web';
        };
        //系统的名称
        window.osName = function () {
            return 'Android';
        };
        setTimeout(function () {
            if (!window.plus && typeof onPageReady === 'function') {
                onPageReady.call(null, webview);
            }
        }, 3000);

        function plusReady() {
            $('.status-bar').css('height', plus.navigator.getStatusbarHeight() * 2 + 'px');
            removeLocalItem('openWebview');
            plus.key.hideSoftKeybord();
            //原生支持方法封装
            window.exit = function () {
                ('iOS' == plus.os.name) ? plus.nativeUI.confirm('确认退出？', function (e) {
                    if (e.index > 0) {
                        plus.runtime.quit();
                    }
                }, '政策在手', ['取消', '确定']) : (confirm('确认退出？') && plus.runtime.quit());
            };
            window.log = function () {
                plus.nativeUI.toast(JSON.stringify(arguments));
            };
            window.currentWebview = function () {
                return plus.webview.currentWebview();
            };
            window.openWebview = function (id, params, showed) {
                //webview[id].styles.top = plus.navigator.getStatusbarHeight() + 'px';
                webview[id].styles.bottom = '0px';
                if (getLocalItem('openWebview')) {
                    return false;
                }
                setLocalItem('openWebview', true);
                if (typeof webview[id].auth === 'function' && webview[id].auth() === false) {
                    removeLocalItem('openWebview');
                    return false;
                }
                if (plus.webview.getWebviewById(id)) {
                    plus.webview.show(id, "none", 0, showed || defShowed);
                } else {
                    plus.webview.open(webview[id].url + "?" + $.objToParam(params), id, webview[id].styles || defStyles, webview[id].aniShow || defAniShow, defDuration, showed || defShowed);
                }
            };
            window.closeWebview = function (id, aniClose) {
                id ? plus.webview.close(id, aniClose || "auto") : plus.webview.close(plus.webview.currentWebview().id, aniClose || "auto");
            };
            window.reloadWebview = function (id) {
                id ? (plus.webview.getWebviewById(id) && plus.webview.getWebviewById(id).reload(true)) : plus.webview.currentWebview().reload(true);
            };
            window.reloadLaunchWebview = function () {
                reloadWebview(plus.webview.getLaunchWebview().id);
            };
            window.logout = function () {
                removeLocalItem("user");
                evalJs("my-index", 'reload()');
                reloadWebview("my-setup");
            };
            window.tokenExpires = function () {
                logout();
                var id = currentWebview().id;
                if (id === 'my-index') {
                    reloadWebview(id);
                } else {
                    openWebview("account-login");
                    closeWebview(id, "none");
                }
            };
            setTimeout(function () {
                removeLocalItem("toasting");
            }, 2000);
            var toastList = [];
            var toasting = false;

            function runToast() {
                if (!toasting && toastList.length > 0 && new Date().getTime() < toastList[toastList.length - 1].date.getTime() + 2000) {
                    toasting = true;
                    var toastItem = toastList.shift();
                    options = toastItem.options || {};
                    options.align = "center";
                    options.duration = "short";
                    options.icon = "";
                    options.style = "block";
                    options.type = "text";
                    options.richTextStyle = {};
                    options.verticalAlign = "bottom";
                    plus.nativeUI.toast(toastItem.message, options);
                    setTimeout(function () {
                        toasting = false;
                        runToast();
                    }, 2000);
                }
            }

            window.toast = function (message, options) {
                toastList.push({message: message, options: options, date: new Date()});
                runToast();
            };
            window.play = function (url) {
                var Intent = plus.android.importClass("android.content.Intent");
                var Uri = plus.android.importClass("android.net.Uri");
                var main = plus.android.runtimeMainActivity();
                var intent = new Intent(Intent.ACTION_VIEW);
                var uri = Uri.parse(url);
                intent.setDataAndType(uri, "video/*");
                main.startActivity(intent);
            };
            window.dial = function (number, confirm) {
                plus.device.dial(number, confirm || false);
            };
            window.setLocalItem = function (key, item) {
                plus.storage.setItem(key, JSON.stringify(item));
            };
            window.getLocalItem = function (key) {
                return plus.storage.getItem(key) ? JSON.parse(plus.storage.getItem(key)) : false;
            };
            window.removeLocalItem = function (key) {
                plus.storage.removeItem(key);
            };
            window.showWaiting = function () {
                //plus.nativeUI.showWaiting();
            };
            window.closeWaiting = function () {
                plus.nativeUI.closeWaiting();
            };
            window.previewImage = function (urls, current, loop) {
                var options = {background: "#000000", current: current || 0, indicator: "default", loop: loop || false};
                plus.nativeUI.previewImage(urls, options);
            };
            window.share = function (service, title, href, thumb, extra) {
                if (!service.authenticated) {
                    service.authorize(function () {
                        service.send({
                            title: title,
                            href: href,
                            thumbs: ['_www/img/logo.png'],
                            extra: extra || {}
                        }, function () {
                            alert("分享成功！");
                        }, function (e) {
                            alert("分享失败！");
                        });
                    }, function (e) {
                    });
                } else {
                    service.send({
                        title: $.trim(title),
                        href: href,
                        thumbs: ['_www/img/logo.png'],
                        extra: extra || {}
                    }, function () {
                        alert("分享成功！");
                    }, function (e) {
                        alert("分享失败！");
                    });
                }
            };
            window.evalJs = function (id, js) {
                var wv = plus.webview.getWebviewById(id);
                wv && wv.evalJS(js);
            };
            // 从相册中选择图片
            window.galleryImg = function (callback) {
                plus.gallery.pick(function (path) {
                    typeof callback === 'function' && callback.apply(null, arguments);
                }, function (e) {
                }, {filter: "image"});
            };
            window.upload = function (url, path, callback) {
                var task = plus.uploader.createUpload(api_url + url, {},
                    function (t, status) {
                        // 上传完成
                        if (status == 200) {
                            var result = new Result(JSON.parse(t.responseText));
                            if (result.code == '0') {
                                toast('上传成功');
                                typeof callback === 'function' && callback(result.data.url);
                            } else {
                                toast(result.msg);
                            }
                        } else {
                            toast('上传失败');
                        }
                    }
                );
                task.addFile(path, {key: "file"});
                var user = getLocalItem("user");
                if (user) {
                    task.setRequestHeader('token', user.token);
                }
                task.start();
            };
            //图片压缩
            window.compressImage = function (src, name, callback) {
                plus.zip.compressImage({
                    src: src,
                    width: '100px',
                    height: 'auto',
                    overwrite: true,
                    dst: '_downloads/' + name + '.png',
                    format: "png"
                }, function (event) {
                    typeof callback === 'function' && callback(event.target);
                }, function (error) {
                    typeof callback === 'function' && callback(src);
                });
            };
            //获取客户端推送标识信息
            window.getClientInfo = function () {
                var clientInfo = plus.push.getClientInfo();
                return clientInfo && clientInfo.token;
            };
            //系统的名称
            window.osName = function () {
                return plus.os.name === 'iOS' ? 'ios' : 'android';
            };
            //执行页面独有脚本
            if (typeof onPageReady === 'function') {
                onPageReady.call(null, webview);
            }
            // 隐藏滚动条
            plus.webview.currentWebview().setStyle({scrollIndicator: 'none'});
            // Android处理返回键
            plus.key.addEventListener('backbutton', function () {
                switch (plus.webview.currentWebview().id) {
                    case "common-footer": {
                        break;
                    }
                    case "home-index": {
                        exit();
                        break;
                    }
                    case "policies-index": {
                        exit();
                        break;
                    }
                    case "times-index": {
                        exit();
                        break;
                    }
                    case "videos-index": {
                        exit();
                        break;
                    }
                    case "my-index": {
                        exit();
                        break;
                    }
                    default: {
                        closeWebview(plus.webview.currentWebview().id);
                    }
                }
            }, false);
            removeLocalItem('openWebview');
            setViewport();
        }

        //分页组件
        window.initPage = function (scroll, container, list, ajaxParam, lastRecordIdTarget, message, tolerant, waitingTime) {
            lastRecordIdTarget = lastRecordIdTarget || "lastRecordId";
            message = message || {};
            message.load = message.load || "上拉加载...";
            message.refresh = message.refresh || "下拉刷新...";
            message.refreshing = message.refreshing || "刷新中...";
            message.noMore = message.noMore || "没有更多...";
            tolerant = tolerant || 10;
            waitingTime = waitingTime || 1000;
            var isLastRecord = false, lastRecordId = 0, wait = false, pullRefresh = false, _success = ajaxParam.success,
                up = $("<div class=\"down lib-flex-row-center\"></div>"),
                down = $("<div class=\"up lib-flex-row-center\"></div>");
            ajaxParam.error = function () {
                up.html(message.noMore).css("display", "flex").appendTo(list);
                //$(scroll).scrollTop(9999999999);
                down.hide();
            };
            ajaxParam.success = function (data, textStatus, jqXHR) {
                up.hide();
                //down.hide();
                _success(data, textStatus, jqXHR);
                if ($(list).outerHeight(true) <= $(container).height() && isLastRecord !== lastRecordId) {
                    getList();
                } else if (isLastRecord === lastRecordId) {
                    up.html(message.noMore).css("display", "flex").appendTo(list);
                    //$(scroll).scrollTop(9999999999);
                }
            };

            function getList() {
                if (isLastRecord !== lastRecordId) {
                    isLastRecord = lastRecordId;
                    var param = $.extend({}, ajaxParam);
                    param.data[lastRecordIdTarget] = lastRecordId || "";
                    ajax(param);
                } else {
                    if (down.css("display") === "none") {
                        up.html(message.noMore).css("display", "flex").appendTo(list);
                    }
                    //$(scroll).scrollTop(9999999999);
                }
            }

            function refresh(obj) {
                try {
                    ajaxParam.data = $.extend(ajaxParam.data, obj);
                    isLastRecord = false;
                    lastRecordId = 0;
                    wait = false;
                    pullRefresh = false;
                    $(list).empty();
                    typeof window.onRefresh === 'function' && onRefresh();
                    down.html(message.refreshing).css("display", "flex").prependTo(list);
                    getList();
                    $('.search-bar').removeClass('scroll');
                } catch (e) {
                    log(e.toString());
                }
            }

            /*$(scroll).scroll(function () {
                var $search_bar = $('.search-bar');
                var $banner = $('.banner');
                var scrollTop = $(scroll).scrollTop();
                if ($(scroll).scrollTop() === 0) {
                    $search_bar.removeClass('scroll');
                } else {
                    $search_bar.addClass('scroll');
                    if (scrollTop < $banner.outerHeight(true) - $search_bar.outerHeight(true)) {
                        $('.search-bar.scroll').css('background', 'rgba(255,255,255,' + (scrollTop / ($banner.outerHeight(true) - $search_bar.outerHeight(true))) + ')');
                    } else {
                        $('.search-bar.scroll').css('background', 'rgba(255,255,255,1)');
                    }
                }

                if (!wait) {
                    wait = true;
                    setTimeout(function () {
                        wait = false;
                        if ($(scroll).scrollTop() + $(scroll).height() + tolerant >= $(container).outerHeight(true)) {
                            getList();
                        } else {
                            down.hide();
                        }
                    }, waitingTime);
                }
                if (isLastRecord !== lastRecordId) {
                    up.html(message.load).css("display", "flex").appendTo(list);
                }
            });*/
            var from = 0, to = 0, moveInterval = false, step = 0, moveTodo = false, moveStep = function (_to) {
                to = _to;
                step = (to > from ? 100 : -100);//Math.floor((to - from) / 4);
                moveInterval || (moveInterval = setInterval(function () {
                    if (Math.abs(to - from) < Math.abs(step)) {
                        from = to;
                        clearInterval(moveInterval);
                        moveInterval = false;
                        typeof moveTodo === 'function' && moveTodo();
                        moveTodo = false;
                    } else {
                        from = from + step;
                    }
                    if (from > 0) {
                        down.html(message.refresh).css("display", "flex").prependTo(list);
                    }
                    down.css("height", from + "px");

                }, 40));
            };
            $(container).on('touchstart', function (e) {
                var st = $(scroll).scrollTop();
                if ($(scroll).scrollTop() === 0) {
                    var touch = e.originalEvent,
                        startX = touch.changedTouches[0].pageX, startY = touch.changedTouches[0].pageY;
                    $(container).on('touchmove', function (e) {
                        e.preventDefault();
                        touch = e.originalEvent.touches[0] ||
                            e.originalEvent.changedTouches[0];
                        moveStep(touch.pageY > startY ? Math.floor(touch.pageY - startY) : 0);
                        if (touch.pageY - startY < 0) {
                            $(scroll).scrollTop(st + startY - touch.pageY);
                        }
                        if (touch.pageY > startY) {
                            up.hide();
                            pullRefresh = true;
                        } else {
                            pullRefresh = false;
                        }
                    });
                }
            }).on('touchend', function () {
                $(container).off('touchmove');
                if (pullRefresh) {
                    moveTodo = refresh;
                } else {
                    moveTodo = false;
                }
                moveStep(0);
            });
            getList();
            return {
                setLastRecordId: function (id) {
                    lastRecordId = id;
                },
                refresh: refresh
            };
        };
        //图片预览
        window.initPreview = function (target, data_src) {
            $(document).off('click', preview);
            var src = data_src ? 'data-src' : 'src';
            var images = {urls: [], index: {}};
            $(target).each(function () {
                var $this = $(this);
                images.urls.push($this.attr(src));
                images.index[$this.attr(src)] = images.urls.length - 1;
            });
            var preview = function () {
                var $this = $(this);
                plus.nativeUI.previewImage(images.urls, images.index[$this.attr(src) || 0]);
            };
            $(document).on('click', target, preview);
        };
        //监听原生支持生效
        if (window.plus) {
            plusReady();
        } else {
            document.addEventListener('plusready', plusReady, false);
        }
    })(375, 100);
});